<script setup lang="ts">

import {ref,inject,watch,computed } from "vue";
import car from "@/api/warehouse/car";
import jsonBig from "json-bigint";
import {saveAs} from 'file-saver';
const columns = ref([
  {title: 'FBA', dataIndex: 'fba',},
  {title: 'PO-NUMBER', dataIndex: 'po_number',},
  {title: '箱数', dataIndex: 'cnts',},
  {title: '柜号', dataIndex: 'reference_number',},
]);
const carlist_data = inject('carlist_data')
const baseinfo_data = inject('baseinfo_data')
const data = computed(()=>{
  return carlist_data != undefined && carlist_data.value.length > 0 ? carlist_data.value :[]
});

function readTextFromFile(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();

      reader.onload = function (event) {
        resolve(event.target.result);
      };

      reader.onerror = function (error) {
        reject(error);
      };

      reader.readAsText(file, 'utf-8');
    });
  }

const download = async () => {
  let response = await car.execl(baseinfo_data.value.id)
  let contentType = response.headers['content-type'].toLowerCase().split(';')[0];
  if (contentType.includes('json')) {
      let responseText = await readTextFromFile(response.data)
      response.data = JSON.parse(JSON.stringify(jsonBig({storeAsString: true}).parse(responseText)));
      if (response.data.success === false) {
        Message.error(response.data.message)
        return
      }
    }
    let disposition = response.headers['content-disposition'].split(';')[2].split('=')[1].split('\'')[2]
    saveAs(new Blob([response.data], {type: contentType}), decodeURIComponent(disposition))
}

</script>
<template>
  <a-grid-item :span="{ xs: 1, sm: 6}" class="g-collapse">
  <a-collapse :default-active-key="['1']">
    <a-collapse-item header="卡车单信息" key="1" class="g-collapse-no-p">
      <template #extra>
        <a-popconfirm
        content="确定要下载吗?"
        position="bottom"
        @click.stop=""
        @ok="download()"
    >
      <a-button type="primary"  size="mini" v-auth="['warehouse:car:execl']"><icon-download />下载</a-button>
    </a-popconfirm>
        

      </template>
      <a-table :columns="columns" :data="data" :bordered="false" :pagination="false" column-resizable class="income-list"></a-table>
    </a-collapse-item>
  </a-collapse></a-grid-item>
</template>